package utils;

import ru.ipo.dces.clientservercommunication.*;
import ru.ipo.dces.exceptions.GeneralRequestFailureException;
import ru.ipo.dces.exceptions.ServerReturnedError;
import ru.ipo.dces.server.ServerFacade;
import ru.ipo.dces.utils.FileSystemUtils;

import javax.servlet.*;
import java.io.*;

public class DummyPHPServer implements ServerFacade {

    private GenericServlet sourceServlet;

    public DummyPHPServer(GenericServlet servlet) {
        sourceServlet = servlet;
    }

    @Override
    public <T> T doRequest(Request request) throws ServerReturnedError, GeneralRequestFailureException {
        if (request instanceof GetContestDataRequest) {
            GetContestDataResponse response = new GetContestDataResponse();
            response.contest = new ContestDescription();
            response.contest.contestID = 777;
            try {
                String problemsFilePath = sourceServlet.getServletConfig().getServletContext().getRealPath("/") +
                        "/WEB-INF/PHPServerData/Problems/test_problem1.zip";
                LoggerFactory.getLoggerForServlet(sourceServlet).info("IN DUMMY");
                File problemsFile = new File(problemsFilePath);
                if (problemsFile.exists()) {
                    response.problems = new ProblemDescription[1];
                    response.problems[0] = new ProblemDescription();
                    response.problems[0].problem = FileSystemUtils.loadBytesFromFile(problemsFile);
                }
            } catch (IOException e) {
                try {
                    LoggerFactory.getLoggerForServlet(sourceServlet).info(e.getMessage());
                } catch (IOException ignore) {
                }
            }
            return (T) response;
        }

        if (request instanceof DownloadPluginRequest) {
            DownloadPluginResponse response = new DownloadPluginResponse();
            try {
                String pluginsFilePath = sourceServlet.getServletConfig().getServletContext().getRealPath("/") +
                        "/WEB-INF/PHPServerData/Plugins/test_plugin1.jar";
                File pluginsFile = new File(pluginsFilePath);
                if (pluginsFile.exists())
                    response.pluginBytes = FileSystemUtils.loadBytesFromFile(pluginsFile);

            } catch (IOException e) {
                try {
                    LoggerFactory.getLoggerForServlet(sourceServlet).info(e.getMessage());
                } catch (IOException ignore) {
                }
            }
            return (T) response;
        }
        return null;
    }
}
